const pageData = require('../config/pageKeys.js');

function Page() {
    this.pageView = new Map();
    this.state = '未知';

    // Sort pageData based on k_text length
    pageData.sort(function (a, b) {
        return b.k_text.length - a.k_text.length;
    });
}

// Add methods to the Page class
Page.prototype.analysisText = function (ocrArray) {
    let state = '未知';
    for (let index = 0; index < pageData.length; index++) {
        let match = true;
        let element = pageData[index];
        // Check if all key texts are present in the OCR array
        for (let j = 0; j < element.k_text.length; j++) {
            let keyText = element.k_text[j];
            let isMatch = false;

            for (let i = 0; i < ocrArray.length; i++) {
                let pngItem = ocrArray[i];

                if (pngItem.text.includes(keyText)) {
                    isMatch = true;
                    this.pageView.set(keyText, pngItem);
                    break;
                }
            }

            if (!isMatch) {
                match = false;
                break;
            }
        }
        if (match) {
            state = element.state;
            break;
        }
    }
    this.state = state;
    console.log('页面状态: ' + state);
};

Page.prototype.toView = function () {
    // Implement view logic if needed
};

Page.prototype.click = function (key) {
    // Enable accessibility service with toast
    if (!auto.service) {
        toast('无障碍服务未启动');
        return false;
    }

    let info = this.pageView.get(key);
    console.log('点击信息', key, !!info);

    if (!info) {
        return false;
    }

    // Click on the specified coordinates
    click(info.bounds.left, info.bounds.bottom);
    return true;
};

// Export the Page class as a module
module.exports = Page;
